﻿using System;
using System.IO;
using System.Web;

namespace SupDataSync.Common
{
    public class LogHelper
    {
        private static string logPath = string.Empty;
        /// <summary>
        /// 保存日志的文件夹
        /// </summary>
        public static string LogPath
        {
            get
            {
                if (logPath == string.Empty)
                {
                    if (HttpContext.Current == null)
                        logPath = AppDomain.CurrentDomain.BaseDirectory + @"Log\";
                    else
                        logPath = AppDomain.CurrentDomain.BaseDirectory + @"bin\Log\";
                }
                return logPath;
            }
        }

        private static string logFielPrefix = string.Empty;
        /// <summary>
        /// 日志文件前缀
        /// </summary>
        public static string LogFielPrefix
        {
            get { return logFielPrefix; }
            set { logFielPrefix = value; }
        }

        /// <summary>
        /// 写日志
        /// </summary>
        public static void WriteLog(string logType, string msg, string sql = "")
        {
            System.IO.StreamWriter sw = null;
            try
            {
                string filePath = LogPath + logType + @"\";
                if (Directory.Exists(filePath) == false)
                    Directory.CreateDirectory(filePath);

                sw = System.IO.File.AppendText(filePath + LogFielPrefix + DateTime.Now.ToString("yyMMdd") + ".Log");
                sw.WriteLine(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss  ") + msg);
                if(!string.IsNullOrEmpty(sql))
                    sw.WriteLine(DateTime.Now.ToString("Sql=") + sql + "。");
                sw.WriteLine("");
                sw.Close();
            }
            catch
            {
                sw.Close();
            }
        }

        /// <summary>
        /// 写日志
        /// </summary>
        public static void WriteLog(LogType logType, string msg, string sql = "")
        {
            WriteLog(logType.ToString(), msg, sql);
        }
    }

    /// <summary>
    /// 日志类型
    /// </summary>
    public enum LogType
    {
        Trace,
        Error,
        SQL
    }

}